package com.licheedev.serialpathdialog

import android.app.Dialog
import android.content.Context
import android.serialport.SerialPortFinder
import android.view.*
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView


class SerialPathDialog(context: Context) : Dialog(context, R.style.TheSerialPathDialogStyle) {

    private val serialPortFinder = SerialPortFinder()
    private var paths: List<String> = fetchPaths()


    private val adapter = object : RecyclerView.Adapter<VH>() {

        override fun onBindViewHolder(holder: VH, position: Int) {
            holder.path.text = paths[position]
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
            val inflate = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_the_serialport_path, parent, false)

            val vh = VH(inflate)
            vh.itemView.setOnClickListener {
                val pos = vh.adapterPosition
                dismiss()
                action?.invoke(paths[pos])

            }
            return vh
        }

        override fun getItemCount(): Int = paths.size
    }

    init {

        setContentView(R.layout.dialog_the_serialport_path)

        val dialogWindow: Window? = getWindow()
        dialogWindow?.setGravity(Gravity.CENTER)

        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        recyclerView.adapter = adapter

        findViewById<ImageButton>(R.id.btnClose).setOnClickListener {
            dismiss()
        }

    }

    private fun fetchPaths(): List<String> {
        val allDevicesPath = serialPortFinder.getAllDevicesPath()
        return if (allDevicesPath.isEmpty()) listOf("null") else allDevicesPath.asList()
    }


    private var action: ((path: String) -> Unit)? = null

    interface ClickPathListener {
        fun click(path: String)
    }

    fun show(action: (path: String) -> Unit) {
        this.action = action
        paths = fetchPaths()
        adapter.notifyDataSetChanged()
        super.show()
    }

    override fun show() {
        super.show()
        throw IllegalStateException("不要直接调用这个方法，请调用SelectPathDialog.show(action)")
    }


    private class VH(view: View) : RecyclerView.ViewHolder(view) {
        val path = view.findViewById<TextView>(R.id.tvPath)
    }
}